package com.njegovanobradovic.icet.components;

import java.util.LinkedList;
import java.util.List;

import org.apache.tapestry5.*;
import org.apache.tapestry5.annotations.*;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.*;
import org.apache.tapestry5.BindingConstants;

import com.njegovanobradovic.icet.facade.Controller;
import com.njegovanobradovic.icet.metamodel.User;
import com.njegovanobradovic.icet.pages.Details;
import com.njegovanobradovic.icet.pages.Index;

/**
 * Layout component for pages of application icet.
 */
@Import(stylesheet = "context:layout/layout.css")
public class Layout
{
    /** The page title, for the <title> element and the <h1> element. */
    @Property
    @Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
    private String title;

    @Property
    private String pageName;

    @Property
    @Parameter(defaultPrefix = BindingConstants.LITERAL)
    private String sidebarTitle;

    @Property
    @Parameter(defaultPrefix = BindingConstants.LITERAL)
    private Block sidebar;

    @Inject
    private ComponentResources resources;

	@Inject
	@Property
	private Controller controller;
	
	
	
	@Component
	private Form findUserForm;
	@Property
	private String name;
	@Persist
	private List<User> searchList;
	@Property
	private User user;
	@InjectPage
	private Details detailsPage;
	
	public List<User> getSearchList() {
		return searchList;
	}
	public void setSearchList(List<User> searchList) {
		this.searchList = searchList;
	}

	@OnEvent(value = "submit", component = "findUserForm")
	public void onFormSubmit() {
		setSearchList(new LinkedList<User>());
		for (User u : controller.getAllUsers()) {
			if (u.getName().equals(name)||u.getUsername().equals(name)||u.getSurname().equals(name)) {
				getSearchList().add(u);
			}
		}
	}
	
	
	@OnEvent(component = "detailsLink2")
    Object onShowDetails2(String username) {
            detailsPage.setUser(controller.getUser(username));
            return detailsPage;
    }
	

    public String getClassForPageName()
    {
      return resources.getPageName().equalsIgnoreCase(pageName)
             ? "current_page_item"
             : null;
    }

    public String[] getPageNames()
    {
      return new String[] { "Home", "About", "Contact"};
    }
    
    public String getLoginMessage() {
		if (controller.isLoggedIn()){
			return "Welcome, " + controller.getLoggedUser().getName()+"!";
		} else {
			return "You are not loged in. Please log in!";
		}
	}
    
    public Object onSubmitFromLogoutForm() {
    	controller.userLogout();
		return Index.class;
	}
}
